<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:sysWorkflow:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:sysWorkflow:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:sysWorkflow:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:sysWorkflow:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sysWorkflowList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="流程id" align="center" prop="wid" v-if="true"/> -->
      <el-table-column label="名称" align="center" prop="name" width="220" />
      <el-table-column label="描述" align="center" prop="memo"/>
      <!-- <el-table-column label="租户ID" align="center" prop="tenantId" /> -->
      <el-table-column label="状态" align="center" prop="status" width="180">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
       </el-table-column>
      <!-- <el-table-column label="节点配置" align="center" prop="nodes" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:sysWorkflow:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:sysWorkflow:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工作流程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1020px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="memo">
              <el-input v-model="form.memo" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
       <el-row :gutter="15">
         <el-card class="box-card" shadow="hover">
             <div slot="header" class="clearfix">
                 <div class="block_blue"></div>
                 <span>节点配置</span>
                 <el-button type="primary" style="float:right;" size="mini" @click="handleAddNode(form)">增加</el-button>
             </div>
                 <el-row :gutter="15" style="background-color: #d3dce6;">
                   <el-col :span="2"><label>No</label></el-col>
                   <!-- <el-col :span="2"><label>编号</label></el-col> -->
                   <el-col :span="3"><label>名称</label></el-col>
                   <el-col :span="3"><label>经办类型</label></el-col>
                   <el-col :span="5"><label>经办者</label></el-col>
                   <el-col :span="2"><label>转办</label></el-col>
                   <el-col :span="3"><label>转办类型</label></el-col>
                   <el-col :span="5"><label>转办者</label></el-col>
                   <el-col :span="1"><label></label></el-col>
                 </el-row>
                 <template v-for="(node,index) in form.items">
                 <el-row :gutter="15" style="margin-top: 10px;border-top: 1px dashed #d3dce6;padding-bottom: 10px;padding-top: 10px;">
                   <el-col :span="2">
                     <el-input v-model="node.sort" placeholder="顺序"/>
                   </el-col>
                  <!-- <el-col :span="2">
                     <el-input v-model="node.nodeno" placeholder="编号" />
                   </el-col> -->
                   <el-col :span="3">
                     <el-input v-model="node.name" placeholder="名称"/>
                   </el-col>
                   <el-col :span="3">
                      <el-select v-model="node.otype" @change="otypeHandle($event,index)" placeholder="类型" size="small" v-if="node.sflag != 'Y' && node.eflag != 'Y'">
                        <el-option
                          v-for="dict in dict.type.handle_type"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                   </el-col>
                   <el-col :span="5">
                     <el-select v-model="node.objIds" multiple placeholder="选择用户" v-if="node.otype == '0' && node.sflag != 'Y' && node.eflag != 'Y'">
                       <el-option
                         v-for="item in userOptions"
                         :key="item.userId"
                         :label="item.userName"
                         :value="item.userId"
                         :disabled="item.status == 1"
                       ></el-option>
                     </el-select>
                     <el-select v-model="node.objIds" multiple placeholder="选择角色" v-if="node.otype == '1' && node.sflag != 'Y' && node.eflag != 'Y'">
                       <el-option
                         v-for="item in roleOptions"
                         :key="item.roleId"
                         :label="item.roleName"
                         :value="item.roleId"
                         :disabled="item.status == 1"
                       ></el-option>
                     </el-select>
                     <el-input v-model="node.deptName" placeholder="选择部门" v-on:focus="handleFocus(0,index)" v-if="node.otype == '2' && node.sflag != 'Y' && node.eflag != 'Y'"/>
                   </el-col>
                   <el-col :span="2">
                      <el-select v-model="node.zflag" placeholder="转办" size="small" v-if="node.sflag != 'Y' && node.eflag != 'Y'">
                        <el-option
                          v-for="dict in dict.type.sys_yes_no"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                   </el-col>
                   <el-col :span="3">
                     <el-select v-model="node.ttype" @change="ttypeHandle($event,index)" placeholder="类型" v-if="node.sflag != 'Y' && node.eflag != 'Y'">
                     <el-option
                       v-for="dict in dict.type.handle_type"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value"
                     ></el-option>
                   </el-select>
                   </el-col>
                  <el-col :span="5">
                      <el-select v-model="node.tobjIds" multiple placeholder="选择用户" v-if="node.ttype == '0' && node.sflag != 'Y' && node.eflag != 'Y'">
                        <el-option
                          v-for="item in userOptions"
                          :key="item.userId"
                          :label="item.userName"
                          :value="item.userId"
                          :disabled="item.status == 1"
                        ></el-option>
                      </el-select>
                      <el-select v-model="node.tobjIds" multiple placeholder="选择角色" v-if="node.ttype == '1' && node.sflag != 'Y' && node.eflag != 'Y'">
                        <el-option
                          v-for="item in roleOptions"
                          :key="item.roleId"
                          :label="item.roleName"
                          :value="item.roleId"
                          :disabled="item.status == 1"
                        ></el-option>
                      </el-select>
                      <el-input v-model="node.deptTName" placeholder="选择部门" v-on:focus="handleFocus(1,index)" v-if="node.ttype == '2' && node.sflag != 'Y' && node.eflag != 'Y'"/>
                   </el-col>
                   <el-col :span="1">
                     <el-button size="mini" type="text" icon="el-icon-delete"
                       @click="handleDeleteNode(node)" v-if="node.sflag !='Y' && node.eflag !='Y'"></el-button>
                   </el-col>
                   </el-row>
                  </template>
         </el-card>
       </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <el-dialog
            width="30%"
            title="选择部门"
            :visible.sync="drawer"
            append-to-body>
             <el-tree :data="deptOptions" node-key="id" @check-change="handleCheckChange" show-checkbox ref="tree"></el-tree>
             <div slot="footer" class="dialog-footer">
                 <el-button @click="dialogFormVisible">取 消</el-button>
                 <el-button type="primary" @click="dialogFormSure">确 定</el-button>
               </div>
          </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
  import {listSysWorkflow, getSysWorkflow, delSysWorkflow, addSysWorkflow, updateSysWorkflow, initBean,changeWorkflowStatus } from "@/api/system/sysWorkflow";
  import { roleoptionselect } from "@/api/system/role";
  import { getUserSelect } from "@/api/system/user";
  import { treeselect } from "@/api/system/dept";
  export default {
    name: "SysWorkflow",
    dicts: ['handle_type', 'sys_yes_no', 'glo_status'],
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 工作流程表格数据
        sysWorkflowList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 角色选项
        roleOptions: [],
        // 部门树选项
        deptOptions: undefined,
        // 用户选项
        userOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined,
          status: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        //抽屉效果
        drawer:false,
        curEditIndex:undefined,
        curEditType:undefined,
        deptIds:[]
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询工作流程列表 */
      getList() {
        this.loading = true;
        listSysWorkflow(this.queryParams).then(response => {
          this.sysWorkflowList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      otypeHandle(val,index){
        console.log('selectChange',val,index)
        this.form.items[index].objIds=[];
        this.form.items[index].deptName='';
      },
      ttypeHandle(val,index){
        console.log('selectChange',val)
        this.form.items[index].tobjIds=[];
        this.form.items[index].deptTName='';
      },
      handleCheckChange(data, checked, indeterminate) {
        console.log(data, checked, indeterminate);
        console.log(this.form)
      },
      handleFocus(type,index) {
        this.curEditIndex = index;
        this.curEditType = type;
        console.log("Focuse",index);
        this.drawer = true;
      },
      dialogFormSure(){
        this.drawer = false;
        let deptIds = [];
        let detpNames = [];
        this.$refs.tree.getCheckedNodes().forEach(function(item){
          deptIds.push(item.id);
          detpNames.push(item.label);
        });
        if(deptIds.length > 0){
          if(this.curEditType == 0){
            this.form.items[this.curEditIndex].objIds = deptIds;
            this.form.items[this.curEditIndex].deptName = detpNames.join(",");
          }else{
            this.form.items[this.curEditIndex].tobjIds = deptIds;
            this.form.items[this.curEditIndex].deptTName = detpNames.join(",");
          }
        }else{
          if(this.curEditType == 0){
            this.form.items[this.curEditIndex].objIds = [];
            this.form.items[this.curEditIndex].deptName = '';
          }else{
            this.form.items[this.curEditIndex].tobjIds = [];
            this.form.items[this.curEditIndex].deptTName = '';
          }
        }
      },
      dialogFormVisible(){
        this.drawer = false;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要"' + text + '""' + row.name + '"工作流程吗？').then(function() {
          return changeWorkflowStatus(row.wid, row.status);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 表单重置
      reset() {
        this.form = {
          wid: undefined,
          name: undefined,
          memo: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          tenantId: undefined,
          status: "0",
          delFlag: undefined,
          nodes: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.wid)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.loading = true;
        this.reset();
        this.getTreeselect();
        initBean().then(response => {
          this.loading = false;
          this.form = response.data;
          this.open = true;
          this.title = "添加工作流程";
        });
        roleoptionselect().then(response => {
          this.roleOptions = response.data;
        });
        getUserSelect().then(response => {
          this.userOptions = response.data;
        });
      },
      handleAddNode(form){
        let sort = this.form.items.length-1;
        this.form.items.splice(sort, 0, {
            nid:'',
            sort:sort,
            name:'',
            otype:'0',
            zflag:'N',
            ttype:'0',
            nodeno:'',
            objIds:[]
          });
          this.form.items[sort+1].sort=sort+1;
      },
      handleDeleteNode(item){
        var index = this.form.items.indexOf(item)
        if (index !== -1) {
          this.form.items.splice(index, 1)
        }
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        this.getTreeselect();
        const wid = row.wid || this.ids
        roleoptionselect().then(response => {
          this.roleOptions = response.data;
        });
        getUserSelect().then(response => {
          this.userOptions = response.data;
        });
        getSysWorkflow(wid).then(response => {
          this.loading = false;
          this.form = response.data;
          this.open = true;
          this.title = "修改工作流程";
        });

      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.wid != null) {
              updateSysWorkflow(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addSysWorkflow(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const wids = row.wid || this.ids;
        this.$modal.confirm('是否确认删除工作流程？').then(() => {
          this.loading = true;
          return delSysWorkflow(wids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/sysWorkflow/export', {
          ...this.queryParams
        }, `sysWorkflow_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
